package com.yuezhu.versionup;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 操作数据库
 *
 *
 *
 */
public class SQLiteDownDatabase extends SQLiteOpenHelper {

	private static final String DATABASE_NAME = "multiThreadDownload.db";
	private static final int DATABASE_VERSION = 1;
	private static SQLiteDownDatabase dbInstance;

	private SQLiteDatabase mDb;

	/**
	 * 获取单例
	 *
	 * @param context
	 * @return
	 */
	public static SQLiteDownDatabase getInstance(Context context) {
		if (dbInstance == null) {
			dbInstance = new SQLiteDownDatabase(context);
		}
		return dbInstance;
	}

	private SQLiteDownDatabase(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("create table download_info(_id integer PRIMARY KEY AUTOINCREMENT, thread_id integer, "
				+ "start_pos integer, end_pos integer, compelete_size integer, taskId varchar(150),url varchar(150),local_full_path varchar(150))");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// db.execSQL("DROP TABLE IF EXISTS download_info");
		// onCreate(db);
	}

	/**
	 * 查看数据库中是否有数据
	 */
	public synchronized boolean isHasInfors(String taskId) {
		mDb = dbInstance.getWritableDatabase();
		int count = -1;
		try {
			String sql = "select count(*)  from download_info where taskId=?";
			Cursor cursor = mDb.rawQuery(sql, new String[] { taskId });
			if (cursor.moveToFirst()) {
				count = cursor.getInt(0);
			}
		} catch (SQLException e) {
			Log.d("查询出错 ", e.getMessage());
		} finally {
			if (null != mDb) {
				mDb.close();
			}
		}
		return count == 0;
	}

	/**
	 * 保存 下载的具体信息
	 */
	public synchronized void saveInfos(List<DownloadInfoTask> infos) {
		mDb = dbInstance.getWritableDatabase();
		try {
			for (DownloadInfoTask info : infos) {
				String sql = "insert into download_info(thread_id,start_pos, end_pos,compelete_size,taskId,url,local_full_path) values (?,?,?,?,?,?,?)";
				Object[] bindArgs = { info.getThreadId(), info.getStartPos(),
						info.getEndPos(), info.getCompeleteSize(),
						info.getTaskId(), info.getUrl(), info.getLocalFullPath() };
				mDb.execSQL(sql, bindArgs);
			}
		} catch (SQLException e) {
			Log.d("保存出错 ", e.getMessage());
			System.out.println("liu game saveinfos error="+e.getMessage());
		} finally {
			if (null != mDb) {
				mDb.close();
			}
		}
	}

	/**
	 * 得到下载具体信息
	 */
	public synchronized List<DownloadInfoTask> getInfos(String taskId) {
		mDb = dbInstance.getWritableDatabase();
		List<DownloadInfoTask> list = new ArrayList<DownloadInfoTask>();
		try {
			String sql = "select thread_id, start_pos, end_pos,compelete_size,taskId,url,local_full_path from download_info where taskId=?";
			Cursor cursor = mDb.rawQuery(sql, new String[] { taskId });
			while (cursor.moveToNext()) {
				DownloadInfoTask info = new DownloadInfoTask(cursor.getInt(0),
						cursor.getInt(1), cursor.getInt(2), cursor.getInt(3),
						cursor.getString(4), cursor.getString(5), cursor.getString(6));
				list.add(info);
			}
		} catch (SQLException e) {
			Log.d("查询出错 ", e.getMessage());
		} finally {
			if (null != mDb) {
				mDb.close();
			}
		}
		return list;
	}

	/**
	 * 更新数据库中的下载信息
	 */
	public synchronized void updataInfos(int threadId, int compeleteSize,
										 String taskId) {
		mDb = dbInstance.getWritableDatabase();
		try {
			String sql = "update download_info set compelete_size=? where thread_id=? and taskId=?";
			Object[] bindArgs = { compeleteSize, threadId, taskId};
			mDb.execSQL(sql, bindArgs);
		} catch (SQLException e) {
			Log.d("更新出错 ", e.getMessage());
		} finally {
			if (null != mDb) {
				mDb.close();
			}
		}
	}

	/**
	 * 下载完成后删除数据库中的数据
	 */
	public synchronized void delete(String taskId) {
		mDb = dbInstance.getWritableDatabase();
		try {
			mDb.delete("download_info", "taskId=?", new String[] { taskId });
		} catch (SQLException e) {
			Log.d("删除出错 ", e.getMessage());
		} finally {
			if (null != mDb) {
				mDb.close();
			}
		}
	}
	/**
	 * 判断是否完成了任务,如果数据库中无此记录，则返回false
	 * @param url
	 */
	public synchronized boolean finishTask(String taskId) {
		boolean rs = true;
		List<DownloadInfoTask> lists = getInfos(taskId);
		System.out.println("liu download finish lists="+taskId+" "+lists);
		if(null != lists && lists.size() > 0){
			for (DownloadInfoTask downloadInfoTask : lists) {
				//判断结束点,开始点
				System.out.println("liu game finishTask="
						+downloadInfoTask.getEndPos()+" "
						+downloadInfoTask.getStartPos()+" "
						+downloadInfoTask.getCompeleteSize());
				if( downloadInfoTask.getEndPos() - downloadInfoTask.getStartPos() > downloadInfoTask.getCompeleteSize()){
					rs = false;
					break;
				}
			}
		}else{
			rs = false;
		}
		return rs;
	}

}